﻿using System;
using System.Collections.Generic;
using System.Linq;
using Ants;
using SettlersEngine;
using System.Drawing;
using System.IO;

namespace AntsBot
{
    public class GatherFood : Strategy
    {
        public GatherFood(AntLoc ant) : base(StrategyTypes.GatherFood, ant) {  }

        public override Goal GetGoal()
        {
            if (!Ant.State.FoodTiles.Any() && !Ant.State.EnemyAnts.Any())
                return new Scout(Ant).GetGoal();

            Utility.Log("foodtiles: " + Ant.State.FoodTiles.Count);
            // look for some food
            var searchingspots = Ant.State.FoodTiles.Where(f => Ant.State.PersistentState.Goals.Count(g => g.EndPoint.Equals(f)) == 0);
            Utility.Log("searchingspots: " + searchingspots.Count());
            //searchingspots = searchingspots.Where(f => f.GetDistance(ant) < GetSearchRadius(state)).OrderBy(f => f.GetDistance(ant)).Take(2);
            var antpoint = Ant.ToPoint();
            var foodpoints = searchingspots.Select(f => new
            {
                Tile = f,
                Point = f.ToPoint(),
                Distance = Ant.State.GetDistance(Ant, f)//astar.Search(ant.ToPoint(), f.ToPoint(), new Object()) ?? Enumerable.Empty<Tile>()
            });

            var closest = foodpoints.OrderBy(f => f.Distance).FirstOrDefault();

            if (closest != null)
            {
                Utility.Log("closest food:" + closest.Tile);

                return new Goal(closest.Tile, Utility.GetPath(Ant, closest.Tile, Ant.State),
                    (s => !s.HasFood(closest.Tile) || Ant.State.EnemyAnts.Any(e=>Ant.State.GetDistance(Ant,e)<Ant.State.GetDistance(Ant,closest.Tile)) || !closest.Tile.GetClosestAnts().Any(a => a.Equals(Ant)))
                , this.Type);
            }

            if (!Ant.State.EnemyAnts.Any())
                return new SpreadOut(Ant).GetGoal();
            else if(Ant.State.EnemyAnts.Count<Ant.State.MyAnts.Count)
                return new Fight(Ant).GetGoal();
            else
                return new Condense(Ant).GetGoal();
        }
    }
}